<template>
  <view class="index_wrapper">
    <view class="index_bg">
      <!-- 头像区域 -->
      <view class="index_user">
        <image class="index_avatar" :src="isLoggedIn ? userInfo.avatar : '../../static/default-avatar.png'" mode="aspectFill"></image>
        <view class="index_user_info">
          <view class="index_username">{{isLoggedIn ? userInfo.nickname : '未登录'}}</view>
          <view class="index_tip">{{isLoggedIn ? userInfo.introduction : '登录后查看更多信息'}}</view>
        </view>
        <template v-if="isLoggedIn">
          <button class="edit_btn" @tap="handleEdit">编辑资料</button>
          <button class="refresh_btn" @tap="handleRefresh">刷新数据</button>
          <button class="logout_btn" @tap="handleLogout">退出登录</button>
        </template>
        <template v-else>
          <button class="login_btn" @tap="handleLogin">登录</button>
          <button class="register_btn" @tap="handleRegister">注册</button>
        </template>
      </view>
    </view>

    <!-- 状态栏 -->
    <view class="index_bar" v-if="isLoggedIn">
      <view class="index_bar_item">
        <view class="index_bar_item_label">坚持天数</view>
        <view class="index_bar_item_text">30天</view>
      </view>
      <view class="index_bar_item">
        <view class="index_bar_item_label">今日学习</view>
        <view class="index_bar_item_text">{{studyTime}}</view>
      </view>
      <view class="index_bar_item">
        <view class="index_bar_item_label">今日刷题</view>
        <view class="index_bar_item_text">{{questionCount}}题</view>
      </view>
    </view>

    <!-- 未登录提示 -->
    <view class="login_tip" v-else>
      <text>登录后可以查看学习数据和个人信息</text>
    </view>

    <!-- 菜单项 -->
    <view class="index_menu_item" @tap="handleChapter">
      <view class="index_menu_item_text">章节练习</view>
      <image class="index_menu_item_icon" src="../../static/menu_button.svg" mode="aspectFill"></image>
    </view>
  </view>
</template>

<script>
import { userLogout, getUserInfo, getTodayStudyTime, getTodayQuestionCount } from '../../service/api.js';

export default {
  data() {
    return {
      isLoggedIn: false,
      userInfo: {
        yantiId: '',
        nickname: '',
        avatar: '',
        introduction: ''
      },
      studyTime: '0分钟0秒',
      questionCount: 0
    };
  },
  methods: {
    handleLogin() {
      uni.navigateTo({ url: '/pages/login/index' });
    },
    handleRegister() {
      uni.navigateTo({ url: '/pages/login/index' });
    },
    handleChapter() {
      const token = uni.getStorageSync('token');
      if (!token) {
        uni.redirectTo({ url: '/pages/login/index' });
        return;
      }
      uni.navigateTo({
        url: '/pages/subject/index'
      });
    },
    handleEdit() {
      console.log('编辑资料按钮被点击');
      uni.navigateTo({
        url: '/pages/user/edit'
      });
    },
    handleLogout() {
      userLogout().then(() => {
        uni.removeStorageSync('token');
        this.isLoggedIn = false;
        this.userInfo = {
          yantiId: '',
          nickname: '',
          avatar: '',
          introduction: ''
        };
        uni.showToast({ title: '已退出登录', icon: 'success' });
      }).catch(() => {
        uni.showToast({ title: '退出失败', icon: 'none' });
      });
    },
    
    // 获取今日刷题数
    fetchQuestionCount() {
      if (!this.isLoggedIn) return;
      
      getTodayQuestionCount().then((count) => {
        this.questionCount = count;
      }).catch((err) => {
        console.error('获取刷题数失败:', err);
        this.questionCount = 0;
        uni.showToast({ title: '获取刷题数失败', icon: 'none' });
      });
    },
    
    handleRefresh() {
      if (!this.isLoggedIn) return;
      
      uni.showLoading({ title: '数据刷新中...' });
      
      // 并行获取数据
      Promise.all([
        // 重新获取用户信息
        getUserInfo().then((responseData) => {
          this.userInfo = responseData;
          uni.setStorageSync('userInfo', responseData);
        }).catch((err) => {
          console.error('获取用户信息失败:', err);
          uni.showToast({ title: '获取用户信息失败', icon: 'none' });
        }),
        
        // 重新获取学习时间
        getTodayStudyTime().then((seconds) => {
          const minutes = Math.floor(seconds / 60);
          const remainingSeconds = seconds % 60;
          this.studyTime = `${minutes}分钟${remainingSeconds}秒`;
        }).catch((err) => {
          console.error('获取学习时间失败:', err);
          this.studyTime = '0分钟0秒';
          uni.showToast({ title: '获取学习时间失败', icon: 'none' });
        }),
        
        // 重新获取刷题数
        this.fetchQuestionCount()
      ]).then(() => {
        uni.hideLoading();
        uni.showToast({ title: '刷新成功', icon: 'success' });
      }).catch(() => {
        uni.hideLoading();
        uni.showToast({ title: '刷新失败', icon: 'none' });
      });
    },
    
    onLoad() {
      const token = uni.getStorageSync('token');
      this.isLoggedIn = !!token;
      
      if (this.isLoggedIn) {
        // 先显示本地存储的用户信息
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo) {
          this.userInfo = userInfo;
        }
        
        // 并行获取数据
        Promise.all([
          // 获取用户信息
          getUserInfo().then((responseData) => {
            console.log('获取用户信息成功:', responseData);
            this.userInfo = responseData;
            uni.setStorageSync('userInfo', responseData);
          }).catch((err) => {
            console.error('获取用户信息失败:', err);
            uni.showToast({ title: '获取用户信息失败', icon: 'none' });
            // 若失败，显示本地存储的旧数据
            const userInfo = uni.getStorageSync('userInfo');
            if (userInfo) {
              this.userInfo = userInfo;
            }
          }),
          
          // 获取当天学习时间
          getTodayStudyTime().then((seconds) => {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = seconds % 60;
            this.studyTime = `${minutes}分钟${remainingSeconds}秒`;
          }).catch((err) => {
            console.error('获取学习时间失败:', err);
            this.studyTime = '0分钟0秒';
          }),
          
          // 获取今日刷题数
          this.fetchQuestionCount()
        ]);
      }
    }
  }
};
</script>

<style>
/* 背景区域 */
.index_wrapper {
  background: linear-gradient(135deg, rgba(170, 207, 252, 1) 0%, rgba(187, 208, 251, 1) 50%, rgba(178, 236, 248, 1) 100%);
  min-height: 100vh;
}

.index_bg {
  background: #5983ff;
  height: 340rpx;
  border-bottom-left-radius: 60rpx;
  border-bottom-right-radius: 60rpx;
}

/* 用户区域 */
.index_user {
  display: flex;
  align-items: center;
  padding: 80rpx 0rpx 0rpx 30rpx;
}

.index_avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  border: 4rpx solid white;
}

.index_user_info {
  display: flex;
  flex-direction: column;
  margin-left: 20rpx;
}

.edit_btn,
.refresh_btn,
.logout_btn {
  margin-left: 20rpx;
  padding: 8rpx 16rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20rpx;
  color: white;
  font-size: 24rpx;
  border: none;
  outline: none;
}

.refresh_btn {
  background: linear-gradient(135deg, rgba(170, 207, 252, 0.5) 0%, rgba(187, 208, 251, 0.5) 50%, rgba(178, 236, 248, 0.5) 100%);
}

.index_username {
  color: white;
  font-size: 30rpx;
}

.index_tip {
  font-size: 24rpx;
  color: white;
  margin-top: 8rpx;
}

/* 状态栏 */
.index_bar {
  background: white;
  height: 200rpx;
  margin: -100rpx 30rpx 30rpx 30rpx;
  border-radius: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20rpx;
}

.index_bar_item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.index_bar_item_label {
  font-size: 24rpx;
  color: #00000080;
}

.index_bar_item_text {
  font-size: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 菜单项 */
.index_menu_item {
  background: white;
  padding: 40rpx;
  margin: 60rpx 30rpx 30rpx 30rpx;
  border-radius: 20rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
}

.index_menu_item_text {
  flex: 1;
}

.index_menu_item_icon {
  width: 90rpx;
  height: 90rpx;
}

.login_btn,
.register_btn {
  margin-left: 20rpx;
  padding: 8rpx 16rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20rpx;
  color: white;
  font-size: 24rpx;
  border: none;
  outline: none;
}

.register_btn {
  background: linear-gradient(135deg, rgba(170, 207, 252, 0.5) 0%, rgba(187, 208, 251, 0.5) 50%, rgba(178, 236, 248, 0.5) 100%);
}

.login_tip {
  text-align: center;
  padding: 40rpx;
  color: #666;
  font-size: 28rpx;
}
</style>  